<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<fieldset id="root">
    <legend><h1>这是父组件</h1></legend>
    <child1></child1>
    <child2></child2>

</fieldset>
<template id="child1">
    <fieldset>
        <legend><h2>这是child1子组件</h2></legend>
        <p>接受来自child2的消息:{{c1msg}}</p>
    </fieldset>
</template>
<template id="child2">
    <fieldset>
        <legend><h2>这是child2子组件</h2></legend>
        <button @click="sendMsg">向child1发送信息</button>
    </fieldset>
</template>
</body>
</html>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
    //实例化一个Vue对象,用来监听和发送消息
    let singleVue=new Vue();
    let child1={
        template:"#child1",
        data:function(){
            return{
                c1msg:"",
            }
        },
        created:function(){
        //    组件创建完成后会自动触发,我们在此设置消息监听
        //    $on("要监听的消息名字",对象事件触发后的回调函数)
        //    使用箭头函数让this指向child1
//             singleVue.$on("c2_event",(a)=> {
// console.log("监听的c2事件触发了!!!!",a);
// this.c1msg=a;
//             });

            singleVue.$on("c2_event",this.getC2Msg);

        },
        methods:{
            getC2Msg(a){
                this.c1msg=a;
            }
        }

    };
    let child2={
        template:"#child2",
        data:function () {
return {c2Msg:"来自c2的问候"

            }
        },
        methods:{
            sendMsg(){
            //    点击按钮触发
                singleVue.$emit("c2_event",this.c2Msg);
            }
        }

    };


    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    let root =new Vue({
        el:"#root",
        components:{
            child2,
            child1,
        }
    })
</script>
